package com.eystar.pdc.model;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eystar.ext.plugin.tablebind.ModelExt;
import com.eystar.ext.plugin.tablebind.TableBind;

/**
 * 字典 Model
 * 
 * @author Your_Name
 * 
 */
@TableBind(tableName = "t_pdc_dic")
public class Dic extends ModelExt<Dic> {

	private static final long serialVersionUID = 1244431359124317083L;
	public final static Dic dao = new Dic();
	
	/**
	 * 列出字典树形结构，以JSON格式返回
	 * 
	 * @return
	 */
	public JSONArray listDicJson() {
		List<Dic> dics = find(getSqlPara("pdc.dic.findAll"));
		JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();
		object.put("id", "0");
		object.put("text", "字典管理");
		constructJson(dics, "0", object);
		array.add(object);
		return array;
	}

	/**
	 * 递推循环，json形式
	 * 
	 * @param dics
	 * @param parentId
	 * @param object
	 */
	private void constructJson(List<Dic> dics, String parentId, JSONObject object) {
		JSONArray array = new JSONArray();
		for (Dic dic : dics) {
			if (parentId.equals(dic.getStr("parent_id"))) {
				JSONObject child = new JSONObject();
				child.put("id", dic.getStr("id"));
				child.put("text", dic.getStr("dic_value"));
				child.put("code", dic.getStr("dic_code"));
				constructJson(dics, dic.getStr("id"), child);
				array.add(child);
			}
		}
		if (array != null && array.size() > 0) {
			//object.put("state", "closed");
			object.put("children", array);
		}
	}
	
}